<template>
  <div class="all">
    <div class=" text-2xl font-bold text-black my-2">
        {{blogDetail.blog_title}}
    </div>
    <div v-html="blogDetail.blog_content"></div>
    <div v-if="blogDetail.demo_code">
      <div class=" bg-purple-300 rounded-xl p-4 text-white font-bold text-2xl my-4">示例代码</div>
      <button class=" bg-sky-500 p-1 px-3 font-bold hover:bg-sky-600 rounded-xl text-white shadow-md shadow-sky-300 mb-2" @click="runCode"><div class="flex items-center justify-center"><img src="./运行资源.png" alt=""> 运行代码</div></button>
      <span class=" align-super font-bold ml-4">tips: 这只是一个简单配置的html编辑器OvO</span>
      <div class="flex h-full w-full">
        <div class="" id="code-container"></div>
        <div class="" id="code-result">
          <iframe ref="frameDom" id="iframe" frameborder="0"></iframe>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { postBlogDetail , postIncreaseViewcount } from '@/api/blog';
import { useRoute } from 'vue-router';
import { nextTick, onMounted, ref } from "@vue/runtime-core";
import { EditorState, Compartment } from "@codemirror/state";
import { html } from "@codemirror/lang-html";
import { basicSetup } from "codemirror";
import { indentWithTab } from "@codemirror/commands";
import { EditorView, keymap } from "@codemirror/view";
import { dracula } from "@uiw/codemirror-theme-dracula";

/**
 * 示例代码相关
 */
let state = null;
let view = null;
const frameDom = ref();
const runCode = function () {
  if(frameDom.value){
    frameDom.value.srcdoc = view.state.doc.toString();
  }
};
const initDemo = function(doc){
  const darkCodeTips = EditorView.theme(
    {},
    {dark: true}
  );
  const languageConf = new Compartment();
  state = EditorState.create({
    extensions: [
      basicSetup,
      languageConf.of(html()),
      dracula,
      keymap.of([indentWithTab]),
      darkCodeTips
    ],
    doc: doc,
  });
  view = new EditorView({
    state,
    parent: document.querySelector("#code-container"),
  });
  runCode()
}

/**
 * 博客详情
 */
const blogDetail = ref({})

onMounted(()=>{
  let blogid = useRoute().params?.id
  if(blogid != undefined){
    let params = {
      id: blogid
    }
    postBlogDetail(params).then(res=>{
      blogDetail.value = res
      document.title = res.blog_title

      // 阅读量加一
      postIncreaseViewcount(params)

      // v-if 导致的渲染延后.
      nextTick(()=>{
        initDemo(res.demo_code)
      })
    })
  }
})
</script>

<style scoped>

/deep/.cm-editor {
  height: 800px;
}

h1, h2, h3, h4, h5, h6{
  font-weight: bold !important;
}
#code-container{
  height: 100%;
  width: 50%;
}
#code-result {
  height: 800px;
  width: 50%;
}
#iframe {
  height: 100%;
  width: 100%;
}
</style>